<template>
  <div id="Information_temp">
    <el-row :gutter="20">
      <el-col :span="tableParam.navSpan" v-show="tableParam.navSpan !== 0">
        <el-menu :unique-opened="true" @select="selectItem" style="border-right:none;">
          <template v-for="(item,index) in navtree">
            <nav-menu :index="index.toString()" v-if="!item.leaf" :node="item" :key="'nm_'+index" />
            <el-menu-item v-if="item.leaf" :index="item.index" :key="'me_'+index">
              <i class="fa fa-hand-o-right"></i>{{item.name}}
            </el-menu-item>
          </template>
        </el-menu>
      </el-col>
      <el-col :span="24 - tableParam.navSpan">
        <div class="toolbar">
          <el-form inline @submit.native.prevent>
            <el-form-item>
              <el-input placeholder="请输入要搜索的内容" v-model="tableParam._keyword" size="mini"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="search" :disabled="true" size="mini">搜索</el-button>
              <el-button type="primary" icon="plus" @click="recordFormInit(); recordForm.visible = true; recordForm.flag = true;" size="mini">新增</el-button>
              <el-button type="text" @click="tableParam.navSpan === 4 ? tableParam.navSpan = 0: tableParam.navSpan=4;">{{tableParam.navSpan === 4?'隐藏菜单':'显示菜单'}}</el-button>
            </el-form-item>
          </el-form>
        </div>
        <sample-table :data="records" :isloading="tableParam.loading" sortcustom @afterSortChange="sortChange" @selectionChange="selectionChange">
          <sample-table-header slot="header">
            <sample-table-header-selection />
            <sample-table-header-column label="标题" prop="ZK_TITLE" sortable />
            <sample-table-header-column label="编辑" prop="ZK_AUTHOR" sortable />
            <sample-table-header-column label="权重" prop="ZK_SORT" sortable />
            <sample-table-header-column label="发布时间" prop="ZK_PUBDATE" sortable />
            <sample-table-header-column label="最后修改" prop="EB_LASTMODIFY_DATETIME" sortable />
            <sample-table-header-column label="操作" />
          </sample-table-header>
          <sample-table-body slot-scope="scope" :row="scope.row" :index="scope.index" slot="body">
            <sample-table-body-selection />
            <sample-table-body-column prop="ZK_TITLE" />
            <sample-table-body-column prop="ZK_AUTHOR" />
            <sample-table-body-column prop="ZK_SORT" />
            <sample-table-body-column>
              {{$common.ChangeDateFormat_hhmmss(scope.row.ZK_PUBDATE, '-')}}
            </sample-table-body-column>
            <sample-table-body-column>
              {{$common.ChangeDateFormat_hhmmss(scope.row.EB_LASTMODIFY_DATETIME, '-')}}
            </sample-table-body-column>
            <sample-table-body-column>
              <i class="el-icon-edit icon-btn-edit" @click="recordFormInit(); getRecord(scope)"></i>
              <i class="el-icon-delete icon-btn-del" @click="delRecord(scope)"></i>
            </sample-table-body-column>
          </sample-table-body>
        </sample-table>
        <el-col :span="24" class="botton_toolbar">
          <el-button type="danger" :disabled="selection.length === 0" icon="delete" size="mini" @click="batchDelete">
            批量删除<span v-if="selection.length !== 0"> (共{{selection.length}}条)</span>
          </el-button>
          <el-pagination layout="prev, pager, next, jumper, total" :page-size="tableParam.pagesize" :current-page="tableParam.pageno" :total="tableParam.total" @current-change="currentChange" style="float:right;">
          </el-pagination>
        </el-col>
      </el-col>
    </el-row>
    <el-dialog :title="recordForm.flag ? '新增' : '编辑'" :visible="recordForm.visible" width="80%" :show-close="false">
      <el-form ref="recordForm" class="recordForm" label-width="80px" :model="recordForm.record" :rules="recordformRules" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标　题" prop="ZK_TITLE">
              <el-input v-model="recordForm.record.ZK_TITLE" placeholder="请输入标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封　面">
              <el-input v-model="recordForm.record.ZK_COVERIMG" placeholder="请上传封面或填写封面路径"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="类　型" prop="ZK_NAVID">
              <el-select v-model="recordForm.record.ZK_NAVID" placeholder="请选择类型">
                <el-option v-for="item in navlist" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="编　辑" prop="ZK_AUTHOR">
              <el-input v-model="recordForm.record.ZK_AUTHOR" placeholder="请输入编辑人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="权　重">
              <el-input-number v-model="recordForm.record.ZK_SORT" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布时间">
              <el-date-picker v-model="recordForm.record.ZK_PUBDATE" type="datetime" placeholder="请选择发布时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详　情">
              <vue-html5-editor :content="recordForm.record.ZK_DESC" :height="300" @change="updateContent"></vue-html5-editor>
            </el-form-item>
          </el-col>
          <div :id="hidEditor" v-show="false" v-html="recordForm.record.ZK_DESC"></div>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="recordForm.visible = false;">取 消</el-button>
        <el-button type="primary" @click="recordForm.flag ? insertRecord() : updateRecord()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      navtree: [],
      navlist: [],
      selection: [],
      records: [],
      tableParam: {
        keyword: '',
        _keyword: '',
        prop: '',
        order: '',
        pagesize: 15,
        pageno: 1,
        total: 0,
        loading: false,
        keycurrent: 0,
        navSpan: 4,
        action: '',
        // isSearch: false
      },
      recordForm: {
        flag: true,
        record: {
          ZK_ID: '',
          ZK_TITLE: '',
          ZK_DESC: '',
          ZK_AUTHOR: '',
          ZK_PUBDATE: '',
          ZK_SORT: 0,
          ZK_COVERIMG: '',
          ZK_NAVID: '',
          ZK_ATTACHMENT: [],
        },
        visible: false,
        ishidden: false,
        index: -1,
      },
      recordformRules: {
        ZK_TITLE: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        ZK_AUTHOR: [
          { required: true, message: '请选择编辑人', trigger: 'blur' },
        ],
        ZK_NAVID: [{ required: true, message: '请选择类型', trigger: 'blur' }],
      },
      hidEditor: `h_${this.$common.Guid()}`,
      coverimgAction: '#',
    };
  },
  created() {
    this.$http.get('/api/home/navtree').then(res => {
      if (res.data.flag === 'True') {
        this._build(res.data.result);
        if (this.navlist.length > 0) {
          this.tableParam.action = this.navlist[0].value;
          this.query();
        }
      }
    });
    this._recordForm = JSON.stringify(this.recordForm);
  },
  beforeRouteLeave(to, from, next) {
    if (this.recordForm.visible) {
      this.$confirm('信息未保存，是否继续跳转？', '信息未保存', {
        type: 'warning',
      })
        .then(() => {
          next();
        })
        .catch(() => {
          next(false);
        });
    } else {
      next();
    }
  },
  methods: {
    _build(data) {
      data.forEach(item => {
        if (item.ZK_ISLEAF === '1') {
          this.navlist.push({ label: item.ZK_NAME, value: item.ZK_ID });
        }
      });
      this.navtree = this._buildNode(null, data);
    },
    _buildNode(parent, store) {
      const obj = [];
      store.forEach(item => {
        if (!item.ZK_PARENT) {
          /* eslint-disable no-param-reassign */
          item.ZK_PARENT = null;
        }
        if (item.ZK_PARENT === parent) {
          obj.push({
            index: item.ZK_ID,
            name: item.ZK_NAME,
            leaf: item.ZK_ISLEAF === '1',
            children: this._buildNode(item.ZK_ID, store),
          });
        }
      });
      return obj;
    },
    /* eslint-disable no-unused-vars */
    selectItem(index, path) {
      if (index !== this.tableParam.action) {
        this.tableParam.action = index;
        this.tableParam.pageno = 1;
        this.tableParam._keyword = '';
        this.query();
      }
    },
    query() {
      this.tableParam.loading = true;
      this.$http
        .get('/api/information/list', {
          params: {
            NAVID: this.tableParam.action,
            PROP: this.tableParam.prop,
            ORDER: this.tableParam.order,
            PAGESIZE: this.tableParam.pagesize,
            PAGENO: this.tableParam.pageno,
          },
        })
        .then(res => {
          this.tableParam.loading = false;
          if (res.data.flag === 'True') {
            this.tableParam.total = Number.parseInt(res.data.message, 10);
            this.records = res.data.result;
          }
        });
    },
    updateKeyCurrent(command) {
      this.tableParam.dropdown.forEach((item, index) => {
        if (item.key === command) {
          this.tableParam.keycurrent = index;
        }
      });
    },
    selectionChange(sels) {
      const list = [];
      sels.forEach(item => {
        list.push(this.records[item]);
      });
      this.selection = list;
    },
    recordFormInit() {
      if (this.$refs.recordForm) {
        this.$refs.recordForm.resetFields();
      }
      this.recordForm = JSON.parse(this._recordForm);
      this.recordForm.record.ZK_NAVID = this.tableParam.action;
    },
    currentChange(currentPage) {
      if (this.tableParam.pageno !== currentPage) {
        this.tableParam.pageno = currentPage;
        this.query();
      }
    },
    sortChange(s) {
      if (s.sortOrder) {
        this.tableParam.prop = s.sortProp;
        this.tableParam.order = s.sortOrder.includes('desc')
          ? 'descending'
          : 'ascending';
        this.tableParam.pageno = 1;
        this.query();
      }
    },
    dateFormatter(date) {
      if (typeof data !== 'object') {
        /* eslint-disable no-param-reassign */
        date = new Date(date);
      }
      return `${date.getFullYear()}-${date.getMonth()
        + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
    },
    updateContent(_content) {
      this.recordForm.record.ZK_DESC = _content;
    },
    delRecord(scope) {
      this.$confirm('确定删除该文章吗？', '删除提醒', { type: 'warning' })
        .then(() => {
          this.$http
            .post('/api/information/delete', { IDS: scope.row.ZK_ID })
            .then(res => {
              if (res.data.flag === 'True') {
                this.records.splice(scope.index, 1);
                this.$notify({
                  title: '成功',
                  message: '已成功删除一条信息',
                  type: 'success',
                });
              }
            });
        })
        .catch(() => {});
    },
    batchDelete() {
      const ids = [];
      if (this.selection.length === 0) {
        this.$message.error('请先选中需要删除的选项');
        return;
      }
      this.selection.forEach(item => {
        ids.push(item.ZK_ID);
      });
      this.$confirm('确定删除所选文章吗？', '删除警告', { type: 'warning' })
        .then(() => {
          this.$http
            .post('/api/information/delete', { IDS: ids.join(',') })
            .then(res => {
              if (res.data.flag === 'True') {
                this.$notify({
                  title: '成功',
                  message: '已成功删除多条信息',
                  type: 'success',
                });
                this.recordFormInit();
                this.tableParam.pageno = 1;
                this.query();
              }
            });
        })
        .catch(() => {});
    },
    getRecord(scope) {
      this.$http
        .get('/api/information/detail', {
          params: {
            UID: scope.row.ZK_ID,
          },
        })
        .then(res => {
          if (res.data.flag === 'True') {
            res.data.result.ZK_PUBDATE = this.$common.ChangeDateFormat_hhmmss(res.data.result.ZK_PUBDATE, '-');
            this.recordForm.record = res.data.result;
            this.recordForm.flag = false;
            this.recordForm.visible = true;
            this.recordForm.index = scope.index;
          }
        });
    },
    insertRecord() {
      this.$refs.recordForm.validate(valid => {
        if (valid) {
          if (!this.recordForm.record.ZK_DESC) {
            this.$message.warning('请输入文章详情');
            return;
          }
          if (typeof this.recordForm.record.ZK_PUBDATE === 'object') {
            this.recordForm.record.ZK_PUBDATE = this.dateFormatter(
              this.recordForm.record.ZK_PUBDATE,
            );
          }
          if (!this.recordForm.record.ZK_PUBDATE) {
            this.$message.warning('请选择发布时间');
            return;
          }
          this.recordForm.record._ZK_DESC = document.getElementById(
            this.hidEditor,
          ).innerText;
          this.$http
            .post('/api/information/insert', this.recordForm.record)
            .then(res => {
              if (res.data.flag === 'True') {
                this.records.unshift(
                  JSON.parse(JSON.stringify(this.recordForm.record)),
                );
                this.$notify({
                  title: '成功',
                  message: '新增成功',
                  type: 'success',
                });
                this.recordFormInit();
                this.tableParam.pageno = 1;
                this.query();
              }
            });
        } else {
          return false;
        }
      });
    },
    updateRecord() {
      this.$refs.recordForm.validate(valid => {
        if (valid) {
          if (!this.recordForm.record.ZK_DESC) {
            this.$message.warning('请输入文章详情');
            return;
          }
          if (typeof this.recordForm.record.ZK_PUBDATE === 'object') {
            this.recordForm.record.ZK_PUBDATE = this.dateFormatter(
              this.recordForm.record.ZK_PUBDATE,
            );
          }
          if (!this.recordForm.record.ZK_PUBDATE) {
            this.$message.warning('请选择发布时间');
            return;
          }
          this.recordForm.record._ZK_DESC = document.getElementById(
            this.hidEditor,
          ).innerText;
          this.$http
            .post('/api/information/update', this.recordForm.record)
            .then(res => {
              if (res.data.flag === 'True') {
                const form = JSON.parse(JSON.stringify(this.recordForm.record));
                this.records[this.recordForm.index].ZK_TITLE = form.ZK_TITLE;
                this.records[this.recordForm.index].ZK_DESC = form.ZK_DESC;
                this.records[this.recordForm.index].ZK_AUTHOR = form.ZK_AUTHOR;
                this.records[this.recordForm.index].ZK_PUBDATE = form.ZK_PUBDATE;
                this.records[this.recordForm.index].ZK_SORT = form.ZK_SORT;
                this.$notify({
                  title: '成功',
                  message: '更新文章成功',
                  type: 'success',
                });
                this.recordFormInit();
              }
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
#Information_temp .botton_toolbar {
  border: 1px solid #f2f2f2;
  box-shadow: 0 0 5px #f2f2f2;
  padding: 10px;
  margin: 10px 0 20px 0;
}
#Information_temp .botton_toolbar:hover {
  background: #f2f2f2;
  box-shadow: none;
}
#Information_temp .coverimg {
  margin: 0 auto;
  display: block;
}
</style>
